package cuit.demo.controller;

import cuit.demo.Entity.Article;
import cuit.demo.service.MyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@Controller
@RequestMapping("/personalhomepage")
public class ReviseArticleController {

    @Autowired
    private MyService myService;

    // 显示修改文章页面（根据文章 ID 获取文章内容）
    @GetMapping("/revise/{articleId}")
    public String showRevisePage(@PathVariable("articleId") int articleId, Model model) {
        Article article = myService.findArticleById(articleId);
        if (article!= null) {
            model.addAttribute("article", article);
            return "revise";
        } else {
            model.addAttribute("error", "文章不存在");
            return "redirect:/personalhomepage";
        }
    }

    // 处理文章修改提交
    @PostMapping("/revise")
    public String reviseArticle(
            @RequestParam int articleId,
            @RequestParam("articleTitle") String articleTitle,
            @RequestParam("articleText") String articleText,
            @RequestParam(value = "articleAttachment", required = false) MultipartFile articleAttachment,
            Model model) {

        // 先获取原始文章信息
        Article originalArticle = myService.findArticleById(articleId);

        // 处理附件更新逻辑
        if (articleAttachment!= null &&!articleAttachment.isEmpty()) {
            // 如果有新上传的附件，先删除旧附件（如果存在）
            if (originalArticle.getArticle_attachment()!= null &&!originalArticle.getArticle_attachment().isEmpty()) {
                try {
                    Path oldAttachmentPath = Paths.get(originalArticle.getArticle_attachment());
                    Files.deleteIfExists(oldAttachmentPath);
                } catch (IOException e) {
                    e.printStackTrace();
                    model.addAttribute("error", "删除旧附件失败，请重试或联系管理员。");
                    return "redirect:/personalhomepage";
                }
            }

            // 保存新附件到服务器，并更新文章实体中的附件信息
            try {
                // 定义附件保存的路径为D:\attachment，可根据实际情况修改
                String uploadDir = "D:\\attachment";
                Path uploadPath = Paths.get(uploadDir);
                if (!Files.exists(uploadPath)) {
                    Files.createDirectories(uploadPath);
                }

                // 获取原始文件名
                String originalFileName = articleAttachment.getOriginalFilename();
                originalArticle.setAttachment_name(originalFileName);

                // 生成保存文件的完整路径
                String fileExtension = originalFileName.substring(originalFileName.lastIndexOf('.'));
                String uniqueFileName = System.currentTimeMillis() + fileExtension;
                Path filePath = uploadPath.resolve(uniqueFileName);

                // 将文件保存到服务器
                articleAttachment.transferTo(filePath.toFile());

                // 设置文章实体中的附件路径
                originalArticle.setArticle_attachment(filePath.toString());
            } catch (IOException e) {
                e.printStackTrace();
                model.addAttribute("error", "上传新附件失败，请检查以下可能的原因：");
                model.addAttribute("errorDetail1", "1. 确保D盘存在且有足够的可用空间。");
                model.addAttribute("errorDetail2", "2. 检查应用程序是否有写入D:\\attachment目录的权限。");
                model.addAttribute("errorDetail3", "3. 文件可能已损坏或格式不被支持。");
                return "redirect:/personalhomepage";
            }
        } else {
            // 如果没有新上传的附件，保留原始文章的附件信息
            originalArticle.setArticle_attachment(originalArticle.getArticle_attachment());
            originalArticle.setAttachment_name(originalArticle.getAttachment_name());
        }

        // 更新文章的其他基本信息（标题、内容等）
        originalArticle.setArticle_title(articleTitle);
        originalArticle.setArticle_text(articleText);

        boolean updated = myService.updateArticle(articleId, articleTitle, articleText,
                originalArticle.getArticle_attachment(), originalArticle.getAttachment_name());
        if (updated) {
            model.addAttribute("message", "文章修改成功");
        } else {
            model.addAttribute("error", "文章修改失败，请重试");
        }
        return "redirect:/personalhomepage";
    }

}